<template>
  <div class="flex-row autoGrow welcomeContainer">
    <choose-service-account
      :multiple="false"
      @serviceChange="serviceChange"
    >
      <div class="autoGrow welcomeOptions flex-column">
        <div class="toggleOwner">
          <label>
            <input type="radio"
            name="manager"
            value="manager"
            @change="changeGroupType"
            :checked="groupType=='manager'"> 群主
          </label>
          <label>
            <input type="radio"
            name="manager"
            value="member"
            @change="changeGroupType"
            :checked="groupType=='member'"> 非群主
          </label>
          
        </div>
        <search placeholder="请输入关键词" @change="changeSearch"></search>
        <div class="groupListTitle">
          <label><input type="checkbox" v-model="selectAll"> 群（{{checkedGroups.length}}/{{groups.length }}）</label>
        </div>
        <div class="groupList autoGrow">
          <label v-for="(group) in filterGroups" :key="group.id">
            <user-list-item
              :showBadge="false"
              :showLastMessage="false"
              currentUserWxid=""
              :item="group">
              <template v-slot:checkbox>
                <input type="checkbox"
                  :checked="checkedGroups.includes(group.wxid)"
                   
                  class="select"
                  @change="toggleSelect(group)">
              </template>
              <template v-slot:bottomInfo>
                <div>
                  <span>群成员{{group.personnum}} </span>
                  <span>非好友{{group.personnum - group.friendNum}}</span>
                </div>
              </template>
              <template v-slot:attachInfo>
                <div class="fontGrey">
                  {{hasSetingGroups.includes(group.id) ? '已设置' : ''}}
                </div>
              </template>
            </user-list-item>
          </label>
          
        </div>
      </div>
    </choose-service-account>
    <div class="settingOption flex-column">
      <div class="subTitle">条件设置</div>
      <div class="option flex-row">
        <span>群满</span>
        <input type="text" class="layui-input" v-model="minCount">
        <span>人后发欢迎语</span>
      </div>
      <div class="option flex-row">
        <span>间隔时间为：</span>
        <input type="text" class="layui-input" v-model="timeInterval">
        <span>秒</span>
      </div>
      <div class="subTitle">设置欢迎语</div>
      <div class="option flex-row welcomeName">
        <span>欢迎语名称</span>
        <input type="text" class="layui-input" placeholder="请输入" v-model="welcomeName">
      </div>
      <div class="option flex-row welcomeName">
        <span>欢迎语是否@进群成员</span>
        <el-radio-group v-model="atFriend" class="option-at-friend">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>  
      </div>
      <div class="replies autoGrow">
        <messageButtonGroup
            :csid="csid"
            :wxid="service&&service.wxid"
            @create="settingReply"
          />
        <el-divider v-if="replys.length"></el-divider>
        <div class="quick-plane">
          <div class="quick-item" v-for="(reply, index) in replys" :key="index">
            <div class="quick-item-createtime" style="text-align:right">
                <i @click.stop="replys.splice(index,1)" class="el-icon-close quick-item-close"></i>
            </div>
            <messageCard :message="reply" />
          </div>
        </div>
        <!-- <quick-replies title="" :btnsTop="true" 
          :upToStore="false" @change="settingReply" 
          :initReply="editReply&&editReply"
          />  -->
      </div>
      <div class="submit flex-row">
        <button class="layui-btn layui-btn-sm" @click="submitSetting">提交</button>
      </div>
    </div>
    <div class="welcomeList flex-column autoGrow">
      <div class="subTitle">欢迎语</div>
      <div class="listContainer autoGrow">
        <div
          class="recordItem flex-column"
          :key="index"
          v-for="(record, index) in welcomeList">
          <div class="recordItemInfo flex-row">
            <img :src="record.avatar || record.src" alt="">
            <div class="serviceInfo flex-column">
              <div class="flex-row serviceInfoDetail">
                <div class="serviceName">{{service.nick}}</div>
                <div>{{record.msgcontent}}</div>
              </div>
              <div class="fontGrey sendTyeInfo">
                <span>{{record.time}} 配置了{{record.groupCount}}个群, 时间间隔为{{ record.timeinterval }}秒</span>
              </div>
            </div>
            <div class="labels flex-row autoGrow">
              <button
                @click="editSetting(record)"
                class="layui-btn layui-btn-xs">
                编辑
              </button>
              <button
                @click="cancelSetting(record)"
                class="layui-btn layui-btn-danger layui-btn-xs">
                删除任务
              </button>
            </div>
          </div>
          <div class="targetsOperate flex-row">
            <button
                @click="toggleDetail(index)"
                class="layui-btn layui-btn-warm layui-btn-xs">
                {{ record.showDetail ? '收起' : '详细' }}
            </button>
          </div>
          <div class="recordDetail flex-column" v-if="record.showDetail">
            <div class="tabs">
              <button
                  :class="['layui-btn','layui-btn-xs']">
                  已配置群
              </button>
            </div>
            <div class="flex-column targetsList">
              <user-list-item
                v-for="(target, i) in record.groups"
                :key="i"
                :item="target"
                :showBadge="false"
                :showLastMessage="false"
                :showGender="false"
                currentUserWxid=""
              >
                <template v-slot:bottomInfo>
                  <span>群成员{{target.memberCount}} 非好友{{target.memberCount-target.friendsCount}}</span>
                </template>
                <template v-slot:attachInfo>
                  <div class="fontGrey">已发送{{target.msgCnt}}次</div>
                </template>
              </user-list-item>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import ChooseServiceAccount from '@/components/chooseServiceAccount'
import UserListItem from '@/components/userListItem'
import QuickReplies from './quickReplies'
import Search from '@/components/search'
import pinyin from '@/lib/pinyin'

import messageButtonGroup from '@/components/message-button-group'
import messageCard from '@/components/message-card'
import { mapState } from 'vuex'

export default {
  name: 'welcome',
  data() {
    return {
      currentRecord: null,
      service: null,
      selectAll: false,
      atFriend:1,
      groups: [],
      keyword: '',
      groupType: 'manager', // member
      welcomeName: '',
      minCount: '',
      timeInterval:'',
      replys: [],
      welcomeList: [],
      
      editReply:[],
      checkedGroups: [], // 等待选择的群组
      hasSetingGroups:[], // 已经设置的群组
      editSetingGroups:[] // 已经设置但可编辑群组
    }
  },
  components: {
    ChooseServiceAccount,
    UserListItem,
    QuickReplies,
    Search,
    messageButtonGroup,
    messageCard
  },
  methods: {
    reset(){
      this.replys = []
      this.keyword = ''
      this.welcomeName = ''
      this.minCount = '' 
      this.timeInterval = ''
      this.editSetingGroups =  this.checkedGroups = [] 
    },
    async getGroupList(params) {
      try {
        let data = await this.$api.group.list(params);
        this.groups = this.transGroupData(data)
        let settedData = await this.getSettingList({csId: params.csid, wxaccount: params.wxaccount})
        this.groups = this.groups.map(group=>{
          const setted = settedData.filter(g=>{
            const groupList = g.groupList || []
            if (groupList.indexOf(group.wxid)!=-1) {
              return true
            }
            return false;
          }).length
          if (setted) {
            group.welcome = true
          }
          return group
        })
        console.log(this.groups)
      } catch(e) {
        this.$msg(e)
      }
    },
    async getSettingList(params) {
      const data = await this.$api.welcome.list(params)||[]
      let hasSetingGroups = []
      this.welcomeList = data.map(item=>{
          return {
            name: this.service.name,
            avatar: this.service.avatar,
            welcomeName: item.msgcontent || '',
            time: this.formatTime(item.createTime),
            groupCount: item.groupList.length,
            showDetail: false,
            ...item,
            groups: item.groupList.map(group=>{
              hasSetingGroups.push(group.id)
              return {
                name: group.groupname,
                memberCount: group.personnum,
                friendsCount: group.personnum - group.friendNum,
                sendTime: '',
                ...group
              }
            })
          }
      })
      this.hasSetingGroups = hasSetingGroups
      return this.welcomeList
    },
    serviceChange(services) {
      this.service = services[0]
      if (!this.service) return
      this.reset()
      const params = {
        csid: this.service.csid,
        wxaccount: this.service.wxid
      }
      this.getGroupList(params)
      // this.getSettingList({csId: params.csid, wxaccount: params.wxaccount})
    },
    changeGroupType(e) {
      this.groupType = e.target.value
    },
    toggleSelect(group) {
      if (this.checkedGroups.includes(group.wxid)) {
        this.checkedGroups = this.checkedGroups.filter(item=>{
          return item!=group.wxid
        })
      } else {
        this.checkedGroups.push(group.wxid)
      }
    },
    changeSearch(val) {
      this.keyword = val
    },
    settingReply(reply) {
      this.replys.unshift(reply)
    },
    editSetting(record) {
      this.welcomeName = record.msgcontent
      this.minCount = record.memberlimit
      this.timeInterval = record.timeinterval
      const msgextra = JSON.parse(record.msgextra)
      if(msgextra instanceof Array){
        this.replys = msgextra.reverse() 
      }else{
        this.replys = [msgextra]
      }

      const groupList = record.groupList
      this.editSetingGroups = this.checkedGroups = groupList.map(group=>group.id)
      this.atFriend = record.atfriend||0
      this.currentRecord = record
    },
    updateSetting(){
      const limit = Number(this.minCount);
      const interval = Number(this.timeInterval)
      const record = this.currentRecord
      const replys = [...this.replys]
      if (!this.checkedGroups.length) {
        return this.$msg('请选择要设置的群')
      }
      if (!replys.length) {
        return this.$msg('请选择欢迎语内容')
      }
      
      if (isNaN(limit)) {
        return this.$msg('人数条件设置非法')
      }
      if (isNaN(interval)) {
        return this.$msg('时间间隔条件设置非法')
      }
      const groups = this.groups.filter(item=> this.checkedGroups.includes(item.id))
      const atFriend = this.atFriend
      this.$api.welcome.update({
        id:record.id,
        csid: this.service.csid,
        wxaccountid: this.service.wxid,
        memberlimit: limit,
        timeinterval : interval,
        msgextra: JSON.stringify(replys.reverse()),
        msgcontent: this.welcomeName,
        // msgtype: this.reply.msgtype,
        groupList: groups.map(item=>item.groupno),
        atfriend:atFriend
      }).then(data=>{
        this.welcomeList.forEach((item,index)=>{
          if(item.id === record.id){
            this.welcomeList.splice(index,1,{
              name: this.service.name,
              avatar: this.service.avatar,
              welcomeName: data.msgContent || '',
              time: this.formatTime(data.createTime),
              groupCount: data.groupList.length,
              showDetail: false,
              ...data,
              groups: data.groupList.map(_group=>{
                this.hasSetingGroups.push(_group.id)
                return {
                  name: _group.groupname,
                  memberCount: _group.personnum,
                  friendsCount: _group.personnum - _group.friendNum,
                  sendTime: '',
                  ..._group
                }
              })
            })
          }
        })
        
        this.reset()
        this.currentRecord = undefined

        this.$msg('修改成功')
      }).catch(e=>this.$msg(e))
    },
    submitSetting() {

      if(this.currentRecord){
        this.updateSetting()
        return
      }
      const replys = [...this.replys]
      if (!this.checkedGroups.length) {
        return this.$msg('请选择要设置的群')
      }
      if (!replys.length) {
        return this.$msg('请选择欢迎语内容')
      }
      const limit = Number(this.minCount);
      const interval = Number(this.timeInterval)

      if (isNaN(limit)) {
        return this.$msg('人数条件设置非法')
      }
      if (isNaN(interval)) {
        return this.$msg('时间间隔条件设置非法')
      }
      const groups = this.groups.filter(item=> this.checkedGroups.includes(item.id))
      const atFriend = this.atFriend
      this.$api.welcome.insert({
        csid: this.service.csid,
        wxaccountid: this.service.wxid,
        memberlimit: limit,
        msgextra: JSON.stringify(replys.reverse()),
        msgcontent: this.welcomeName,
        timeinterval : this.timeInterval,
        // msgtype: this.reply.msgtype,
        groupList: groups.map(item=>item.groupno),
        atfriend:atFriend
      }).then(item=>{
        
        this.welcomeList.unshift({
            name: this.service.name,
            avatar: this.service.avatar,
            welcomeName: item.msgContent || '',
            time: this.formatTime(item.createTime),
            groupCount: item.groupList.length,
            showDetail: false,
            ...item,
            groups: item.groupList.map(_group=>{
              this.hasSetingGroups.push(_group.id)
              return {
                name: _group.groupname,
                memberCount: _group.personnum,
                friendsCount: _group.personnum - _group.friendNum,
                sendTime: '',
                ..._group
              }
            })
          })
        
        this.reset()
        this.$msg('提交成功')
      }).catch(e=>this.$msg(e))
    },
    cancelSetting(record) {
      this.$api.welcome.cancel({
        settingid: record.id
      }).then(e=>{
        let hasSetingGroups = this.hasSetingGroups
        this.welcomeList = this.welcomeList.filter(item=>{
          try {
            const groupList = item.groupList
            groupList.forEach(group=>{
              hasSetingGroups = hasSetingGroups.filter(_id=>_id!=group.id)
            }) 
          } catch (error) {
            console.log(error)  
          }
          
          return item.id!==record.id
        })
        this.hasSetingGroups = hasSetingGroups
        this.reset()
      }).catch(e=>this.$msg(e))
    },
    toggleDetail(index) {
      const record = this.welcomeList[index];
      this.$set(this.welcomeList, index, {
        ...record,
        showDetail: !record.showDetail
      })
    }
  },
  computed: {
    ...mapState(['uistate','accountMap']),  
    csid(){
      return this.uistate.adminid
    },
    filterGroups(){
      const isShowManager = this.groupType === 'manager'
      const keyword = pinyin.getFullChars(this.keyword).toLocaleLowerCase() 

      return this.groups.filter(item=>{
        const chars = pinyin.getFullChars(item.groupname).toLocaleLowerCase() ;
        if(isShowManager){
          return item.isfirst === 1 && chars.indexOf(keyword)>-1
        }else{
          return item.isfirst !== 1 && chars.indexOf(keyword)>-1
        }
         
      })
      
    },
    accountMapByWxid(){
      let accountMapByWxid = {}
      Object.values(this.accountMap).forEach(item=>{
        accountMapByWxid[item.wxid] = item 
      })
      return accountMapByWxid
    }


  },
  watch: {
    selectAll(val) {
      if (val) {
        this.checkedGroups = this.groups.map(g=>g.wxid)
      } else {
        this.checkedGroups = []
      }
    },
  }
}
</script>

<style scoped>
.quick-plane{
    height: 100%;
    overflow: auto;
    /* padding: 0 10px;
    background: #f1f1f1; */
}
.quick-item{
    padding: 10px 16px;
    background-color: #fff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 5px 0;  
    cursor: pointer; 
    box-shadow: 0px 1px 1px 1px #ddd;
    transition:transform 200ms;
    padding-right: 10px;
}
.option-at-friend .el-radio{
  margin-right: 10px;
}
</style>